<template>
    <popup ref="popupRef" :title="popupTitle" width="500px" @confirm="handleConfirm" :async="true" @close="popupClose">
        <div class="pr-8">
            <el-form ref="formRef" :model="formData" label-width="140px" :rules="formRules" :validate-on-rule-change="false">
                <el-form-item label="审核意见" prop="reason">
                    <el-input v-model="formData.reason" type="textarea" :rows="4" maxlength="200" />
                </el-form-item>
				<el-form-item v-if="props.value == 2" class="w-2/6" label="需求可见范围" prop="cate_ids">
					<div class="w-80">
						<el-checkbox v-model="is_all" label="全部" :validate-event="false" @change="handleChange" />
						<el-select class="w-[280px]" multiple v-model="formData.cate_ids" :disabled="is_all" @change="onCateChange">
							<el-option  v-for="(item) in optionsData.product_cate_list" :label="item.name" :value="item.id.toString()" :key="item.id.toString()"/>
						</el-select>
					</div>
				</el-form-item>
				<div class="pl-[40px] mb-2.5" v-if="props.value == 2">{{ props.area_name }}满足条件的渠道共计：{{ formData.cate_ids.length != 0 ? city_num : 0 }}个</div>
				<el-form-item v-if="props.value == 2" label="允许其他城市可见" prop="is_city">
					<el-radio-group v-model="formData.is_city">
						<el-radio :label="0">否</el-radio>
						<el-radio :label="1">是</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item v-if="props.value == 2 && formData.is_city == 1" label="可见城市" prop="area_ids">
					<el-select class="w-[280px]" multiple v-model="formData.area_ids" @change="onCityChange">
						<el-option v-for="(item) in city_list" :label="item.Name" :value="item.ID.toString()" :key="item.ID.toString()"/>
					</el-select>
				</el-form-item>
				<div class="pl-[40px] mb-2.5" v-if="props.value == 2">其他城市满足条件的渠道共计：{{ (formData.cate_ids.length != 0 && formData.area_ids.length != 0 ) ? other_num : 0 }}个</div>
            </el-form>
        </div>
    </popup>
</template>
<script lang="ts" setup>
	import Popup from '@/components/popup/index.vue'
	import type { FormInstance, FormRules } from 'element-plus'
	import feedback from '@/utils/feedback'
	import {useDictOptions} from "@/hooks/useDictOptions";
	import { productCate} from '@/api/product/product'
	import { getAccessibleChannelCount, getCitiesInSameProvince } from '@/api/demand/lists';
	const formRef = shallowRef<FormInstance>()
	const props = defineProps({
		show: {
			type: Boolean,
			required: true
		},
		value: {
			type: [Number, String],
			required: true,
		},
		area_id: {
			type: [Number, String],
		},
		area_name: {
			type: String
		}
	})

	const {optionsData} = useDictOptions<{
		product_cate_list: any[],
	}>({
		product_cate_list: {
			api: productCate
		}
	})

	const city_num:any = ref(0)
	const other_num:any = ref(0)
	// 	当前城市和分类下的渠道数
	const getChannelCount = async (bol:boolean) => {
		let area_list:any = []
		formData.area_ids.forEach((item:any)=>{
			area_list.push({area_id:item})
		})
		console.log(area_list)
		const res = await getAccessibleChannelCount({
			'cate_ids': formData.cate_ids,
			'access_area': bol? [{area_id: props.area_id}] : area_list,
		})
		console.log(res)
		if (bol) {
			city_num.value = res.count;
		} else {
			other_num.value = res.count;
		}
	}

	//当前省份的所有城市
	const city_list:any = ref([])
	const getProvince = async () => {
		const res = await getCitiesInSameProvince({area_id: props.area_id})
		console.log(res)
		city_list.value = res;
	}
	getProvince();

	const emit = defineEmits<{
		(event: 'update:show', value: boolean): void
		(event: 'confirm', value: any): void
	}>()

	const popupTitle = computed(() => {
		return `审核${props.value==2?'通过':props.value==3?'驳回':''}`
	})

	const formData:any = reactive({
		check_status: 0,
		cate_ids: [],
		reason: '',
		is_city: 0,
		area_ids: []
	})
	const is_all:any = ref(false)
	const handleChange = (val:any) => {
		console.log(val)
		if (val) {
			let arr:any = []
			optionsData.product_cate_list.forEach((item)=>{
				arr.push(String(item.id))
			})
			formData.cate_ids = arr;
		} else {
			formData.cate_ids = [];
		}
		getChannelCount(true)
	}
	const onCateChange = (val:any) => {
		console.log(val)
		getChannelCount(true)
	}
	const onCityChange = (val:any) => {
		console.log(val)
		getChannelCount(false)
	}
	
	const popupRef = shallowRef<InstanceType<typeof Popup>>()

	const formRules = ref({
		reason: [{required: true,message: '请输入审核意见'}],
		cate_ids: [{required: true,message: '请选择需求可见范围'}],
		is_city: [{required: true,message: '请选择其他城市是否可见'}],
		area_ids: [{required: true,message: '请选择城市'}],
	})

	// 数组去重
	const removeDuplicatesWithReduce = (array:any) => {
		return array.reduce((acc: any[], current: any) => {
			if (!acc.includes(current)) {
				acc.push(current);
			}
			return acc;
		}, []);
	}

	const handleConfirm = async () => {
		await formRef.value?.validate()
		console.log(formData)
		let area_list:any = JSON.parse(JSON.stringify(formData.area_ids));
		area_list.push(props.area_id)
		console.log(area_list)
		// 数组去重， 因为有一个是当前需求的id
		area_list = removeDuplicatesWithReduce(area_list)
		console.log(area_list)
		// 去重完 转化为需要传递的参数类型
		let area_obj:any = []
		area_list.forEach((item:any)=>{
			area_obj.push({area_id: item})
		})
		console.log(area_obj)
		emit('confirm', {
			check_status:props.value,
			reason:formData.reason,
			cate_ids: formData.cate_ids,
		 	access_area: area_obj
		})
	}

	const popupClose = () => {
		emit('update:show', false)
		formRef.value?.resetFields()
	}

	watch(
		() => props.show,
		(val) => {
			if (val) {
				popupRef.value?.open()
				if (props.value == 2) {
					formRules.value.reason[0].required = false;
				} else {
					formRules.value.reason[0].required = true;
				}
			} else {
				popupRef.value?.close()
			}
		}
	)
</script>
<style lang="scss" scoped>
::v-deep .el-form-item__error{
	min-width: 280px !important;
}
</style>